let consumptionChart = null;

document.addEventListener('DOMContentLoaded', function() {
    // 初始化图表
    loadConsumptionDistribution();
    
    // 设置标签按钮点击事件
    document.querySelectorAll('.tag-btn').forEach(button => {
        button.addEventListener('click', function() {
            // 移除其他按钮的active类
            document.querySelectorAll('.tag-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // 添加当前按钮的active类
            this.classList.add('active');
            
            // 加载对应标签的数据
            const tagName = this.getAttribute('data-tag');
            console.log(`Tag button clicked: ${tagName}`);
            loadConsumptionDistribution(tagName);
        });
    });
});

function loadConsumptionDistribution(tagName = '') {
    const url = tagName 
        ? `/api/consumption-score-distribution?tag_name=${encodeURIComponent(tagName)}`
        : '/api/consumption-score-distribution';
    
    console.log(`Fetching data from ${url}`);
    
    fetch(url)
        .then(response => {
            console.log('Response status:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Received data:', data);
            if (data.error) {
                throw new Error(data.error);
            }
            updateConsumptionChart(data);
            updateStats(data);
        })
        .catch(error => {
            console.error('Error loading consumption distribution:', error);
            console.error('Error details:', {
                message: error.message,
                stack: error.stack
            });
            // 显示错误信息
            document.getElementById('averageScore').textContent = '-';
            document.getElementById('userCount').textContent = '-';
            // 清除图表
            if (consumptionChart) {
                consumptionChart.destroy();
                consumptionChart = null;
            }
        });
}

function updateConsumptionChart(data) {
    console.log('Updating chart with data:', data);
    const ctx = document.getElementById('consumptionScoreChart').getContext('2d');
    
    // 如果图表已存在，销毁它
    if (consumptionChart) {
        consumptionChart.destroy();
    }
    
    // 创建新图表
    consumptionChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: data.labels,
            datasets: [{
                label: '用户数量',
                data: data.data,
                backgroundColor: 'rgba(54, 162, 235, 0.5)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return `${context.parsed.y} 位用户`;
                        }
                    }
                }
            }
        }
    });
    console.log('Chart updated successfully');
}

function updateStats(data) {
    console.log('Updating stats:', data);
    // 更新平均分
    document.getElementById('averageScore').textContent = data.average;
    
    // 更新用户数量（总和数据数组）
    const totalUsers = data.data.reduce((a, b) => a + b, 0);
    document.getElementById('userCount').textContent = totalUsers;
    console.log('Stats updated successfully');
}
